﻿using System.Reflection;

namespace Away.Jobs;

public static class ConfiguratorExtensions
{
    public static void AddAwayJobs(this IServiceCollectionQuartzConfigurator configurator)
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        var types = assemblies.SelectMany(o => o.DefinedTypes.Where(t => t.GetCustomAttribute<JobAttribute>() != null));

        foreach (var type in types)
        {
            var job = type.GetCustomAttribute<JobAttribute>();
            if (job == null)
            {
                continue;
            }
            configurator.AddJob(type.AsType(), job.JobKey, o =>
            {
                o.WithDescription(job.Description);
                o.StoreDurably();
            });

            var triggers = type.GetCustomAttributes<TriggerAttribute>();
            if (triggers == null)
            {
                continue;
            }

            foreach (var trigger in triggers)
            {
                configurator.AddTrigger(o =>
                {
                    o.ForJob(job.JobKey);
                    o.WithIdentity(trigger.Name, job.Name);
                    o.WithDescription(trigger.Description);
                    o.WithCronSchedule(trigger.Cron);

                    if (trigger.JobDataMap != null)
                    {
                        o.UsingJobData(trigger.JobDataMap);
                    }
                });
            }

        }
    }
}
